import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { VitePWA } from 'vite-plugin-pwa'
import { visualizer } from 'rollup-plugin-visualizer'
import eslint from 'vite-plugin-eslint'
import path from 'path'

export default defineConfig({
  plugins: [
    react({
      // React Fast Refresh 优化
      fastRefresh: true,
      // 启用 React 17+ 的新 JSX 转换
      jsxRuntime: 'automatic',
    }),

    // ESLint 集成 (仅在开发模式下启用)
    process.env.NODE_ENV === 'development' &&
      eslint({
        cache: false,
        include: ['./src/**/*.js', './src/**/*.jsx'],
        exclude: ['node_modules'],
      }),

    // PWA 支持
    VitePWA({
      registerType: 'autoUpdate',
      workbox: {
        globPatterns: [
          '**/*.{js,css,html,ico,png,svg,jpg,jpeg,gif,webp,woff,woff2}',
        ],
        globIgnores: ['**/stats.html'],
        maximumFileSizeToCacheInBytes: 3 * 1024 * 1024, // 3MB
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
            handler: 'CacheFirst',
            options: {
              cacheName: 'google-fonts-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365, // 1 year
              },
            },
          },
          {
            urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,
            handler: 'CacheFirst',
            options: {
              cacheName: 'gstatic-fonts-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365, // 1 year
              },
            },
          },
        ],
      },
      includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'masked-icon.svg'],
      manifest: {
        name: '工时统计管理系统',
        short_name: '工时统计',
        description:
          '专业的工时统计管理系统，支持Excel导入导出、项目分类统计、日期范围筛选、工时记录管理',
        theme_color: '#1890ff',
        background_color: '#ffffff',
        display: 'standalone',
        scope: '/',
        start_url: '/',
        icons: [
          {
            src: 'icon-192x192.png',
            sizes: '192x192',
            type: 'image/png',
          },
          {
            src: 'icon-512x512.png',
            sizes: '512x512',
            type: 'image/png',
          },
        ],
      },
    }),

    // 构建分析工具
    visualizer({
      filename: 'dist/stats.html',
      open: false,
      gzipSize: true,
      brotliSize: true,
    }),
  ].filter(Boolean),

  // 路径别名
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@components': path.resolve(__dirname, './src/components'),
      '@utils': path.resolve(__dirname, './src/utils'),
      '@assets': path.resolve(__dirname, './src/assets'),
      '@styles': path.resolve(__dirname, './src/styles'),
    },
  },

  // 开发服务器配置
  server: {
    port: 4040,
    open: true,
    host: true, // 允许外部访问
    hmr: {
      overlay: false, // 关闭错误覆盖层
    },
    cors: true,
    // 代理配置（如果需要）
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        secure: false,
      },
    },
  },

  // 构建优化
  build: {
    outDir: 'dist',
    target: 'es2015',
    sourcemap: process.env.NODE_ENV === 'development',
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true, // 生产环境删除 console
        drop_debugger: true, // 生产环境删除 debugger
      },
    },
    rollupOptions: {
      // 代码分割
      output: {
        manualChunks: {
          // 将 React 相关库分离
          react: ['react', 'react-dom'],
          // 将 UI 库分离
          antd: ['antd'],
          // 将图表库分离
          charts: ['recharts'],
          // 将工具库分离
          utils: ['date-fns', 'dayjs'],
        },
        // 资源文件命名
        assetFileNames: (assetInfo) => {
          const info = assetInfo.name.split('.')
          let extType = info[info.length - 1]
          if (
            /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)
          ) {
            extType = 'media'
          } else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/i.test(assetInfo.name)) {
            extType = 'img'
          } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
            extType = 'fonts'
          }
          return `static/${extType}/[name]-[hash][extname]`
        },
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
      },
      // 外部依赖
      external: [],
    },
    // 构建大小警告配置
    chunkSizeWarningLimit: 2000,
    // 资源内联阈值
    assetsInlineLimit: 4096,
  },

  // CSS 配置
  css: {
    // CSS 预处理器
    preprocessorOptions: {
      less: {
        modifyVars: {
          // Ant Design 主题定制
          'primary-color': '#1890ff',
          'link-color': '#1890ff',
          'border-radius-base': '6px',
        },
        javascriptEnabled: true,
      },
    },
    // CSS 模块化
    modules: {
      localsConvention: 'camelCaseOnly',
      generateScopedName: '[name]__[local]___[hash:base64:5]',
    },
  },

  // 预构建优化
  optimizeDeps: {
    include: [
      'react',
      'react-dom',
      'antd',
      'date-fns',
      'dayjs',
      'recharts',
      'lucide-react',
    ],
    exclude: ['@vitejs/plugin-react'],
  },

  // 环境变量
  define: {
    __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
    __BUILD_TIME__: JSON.stringify(new Date().toISOString()),
  },

  // 静态资源处理
  assetsInclude: ['**/*.xlsx', '**/*.xls', '**/*.csv'],

  // 开发工具
  esbuild: {
    drop: process.env.NODE_ENV === 'production' ? ['console', 'debugger'] : [],
  },
})
